package com.central.apps.handler.purchase;

import com.central.app.common.base.BaseHandler;
import com.central.app.service.HandlerService;
import com.central.apps.handler.contract.ConUtil;
import com.central.apps.handler.contract.FileSynUtilService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.exception.service.ServiceException;
import com.central.common.util.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 2023/1/6 陈运祥更改
 */
@Component
@Slf4j
public class PurchasePaymentApplyHandler extends BaseHandler {

    @Autowired
    private HandlerService handlerService;
    @Autowired
    private FileSynUtilService fileSynUtilService;
    @Autowired
    private ConUtil conUtil;
    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if ("gq_paymentapply".equals(objName)) {
            Double appleymoney = MapUtils.getDouble(data, "appleymoney");
            if (appleymoney == 0) {
                throw new ServiceException("申请金额不能为0，请修改申请金额在保存！");
            }

        }
    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        //子表表名  aa 关联字段 puid
        /*
        * 将原发票号，逗号隔开的形式更新到主表字段
		2 发票金额，申请金额，付款金额汇总同步到主表字段，主表字段需要增加三个汇总字段
        * */
        if ("gq_paypursumary".equals(objName)) {
            int puid = MapUtils.getIntValue(data, "puid");
            List<Map<String, Object>> list = handlerService.findBySql("select sum(pricetaxtotal) as pricetaxtotals,sum(applymoney) as applymoneys,sum(paidamt) as paidamts from gq_paypursumary where puid=" + puid);

            String pricetaxtotals = MapUtils.getString(list.get(0), "pricetaxtotals");//发票金额合计
            String applymoneys = MapUtils.getString(list.get(0), "applymoneys");//申请金额合计
            String paidamts = MapUtils.getString(list.get(0), "paidamts");//付款金额合计
            Map<String, Object> map = new HashMap<>();
            map.put("id", puid);
            //汇总申请金额，付款金额，发票金额
            if (!ToolUtil.isEmpty(pricetaxtotals)) {
                map.put("pricetaxtotals", pricetaxtotals);
            }
            if (!ToolUtil.isEmpty(applymoneys)) {
                map.put("applymoneys", applymoneys);
            }
            if (!ToolUtil.isEmpty(paidamts)) {
                map.put("paidamts", paidamts);
            }
            //主表汇总发票号字段
            List<Map<String, Object>> list2 = handlerService.findBySql("select pinum from gq_paypursumary where puid=" + puid);
            String pinum = "";
            if (CollectionUtils.isNotEmpty(list2)) {
                StringBuffer sb = new StringBuffer();
                for (Map<String, Object> stringObjectMap : list2) {
                    String pinum1 = MapUtils.getString(stringObjectMap, "pinum");
                    if (!sb.toString().contains(pinum1)) {
                        sb.append(",").append(pinum1);
                    }
                }
                pinum = sb.toString().replaceFirst(",", "");
            }else {
                pinum=null;
            }
            map.put("invoicecount",list2.size());//发票张数
            map.put("invoicenums", pinum);//发票号统计
            handlerService.update("gq_paymentapply", map);
        }
        //主表保存后，判断合同编号是否为空，如果为空，将合同对应的子表数据删除，合同使用的主表字段清空
        if("gq_paymentapply".equals(objName)){
            if(ToolUtil.isEmpty(data.get("concode"))){
               handlerService.updateBySql("update gq_paymentapply set receivingamounttax=null where id = "+data.get("id"));
               handlerService.updateBySql("delete from gq_concolldetailed where receivingdetailid = "+data.get("id"));
            }
            //获取发票号，查询发票号对应的发票主键id，将附件转移到付款申请
            String invoicenums = MapUtils.getString(data,"invoicenums");
            if(ToolUtil.isNotEmpty(invoicenums)){
                String[] nums = invoicenums.split(",");
                StringBuffer ids = new StringBuffer();
                for (String num : nums) {
                    Map<String,Object> purchaseinvoice = handlerService.findOneBySql("select id from gq_purchaseinvoice where pinum ='"+num+"'");
                    ids.append(purchaseinvoice.get("id"));
                }
                conUtil.moveFile("conpurchaseinvoiceApp",ids.toString(),"conpaymentapplyApp",MapUtils.getIntValue(data,"id"));
            }

        }
        if ("gq_concolldetailed".equals(objName)) {
            int id = MapUtils.getIntValue(data, "receivingdetailid");//主表id
            List<Map<String, Object>> list = handlerService.findBySql("select id ,invoiceid,invoicemoney  from gq_concolldetailed where receivingdetailid=" + id);
            String pinum = "";
            BigDecimal invoicemoneys = new BigDecimal(0);
            if (CollectionUtils.isNotEmpty(list)) {

                StringBuffer sb = new StringBuffer();
                for (Map<String, Object> stringObjectMap : list) {
                    invoicemoneys = invoicemoneys.add(new BigDecimal(MapUtils.getString(stringObjectMap,"invoicemoney")));
                    String pinum1 = MapUtils.getString(stringObjectMap, "invoiceid");
                    if (!sb.toString().contains(pinum1)) {
                        sb.append(",").append(pinum1);
                    }
                }
                pinum = sb.toString().replaceFirst(",", "");
                Map<String, Object> map = new HashMap<>();
                map.put("invoicecount",list.size());//发票张数
                map.put("invoicenums", pinum);//发票号统计
                map.put("pricetaxtotals",invoicemoneys);//累计发票金额之和
                map.put("id", id);//
                handlerService.update("gq_paymentapply", map);
            }

        }

    }
    @Override
    public void beforDelete(String app, String objName, Long id, boolean isLogic) {
        if ("gq_concolldetailed".equals(objName)) {
            //int id = MapUtils.getIntValue(data, "receivingdetailid");//主表id
            //查询主表主键id，用于进行最新的子表统计
            List<Map<String, Object>> list2 = handlerService.findBySql("select receivingdetailid  from gq_concolldetailed where id=" + id);
           int receivingdetailid = MapUtils.getIntValue(list2.get(0),"receivingdetailid");//关联主键id
            List<Map<String, Object>> list = handlerService.findBySql("select id ,invoiceid,invoicemoney,receivingdetailid  from gq_concolldetailed where receivingdetailid=" + receivingdetailid+" and id !="+id);

            String pinum = "";
            BigDecimal invoicemoneys = new BigDecimal(0);
            //查询主表
            if (CollectionUtils.isNotEmpty(list)) {
                StringBuffer sb = new StringBuffer();
                for (Map<String, Object> stringObjectMap : list) {
                    invoicemoneys = invoicemoneys.add(new BigDecimal(MapUtils.getString(stringObjectMap,"invoicemoney")));
                    String pinum1 = MapUtils.getString(stringObjectMap, "invoiceid");
                    if (!sb.toString().contains(pinum1)) {
                        sb.append(",").append(pinum1);
                    }
                }
                pinum = sb.toString().replaceFirst(",", "");

            }
            Map<String, Object> map = new HashMap<>();
            map.put("invoicecount",list.size());//发票张数
            map.put("invoicenums", pinum);//发票号统计
            map.put("pricetaxtotals",invoicemoneys);//统计发票金额，跟采购发票保持一致
            map.put("id", receivingdetailid);//
            try {
                handlerService.update("gq_paymentapply", map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if ("gq_paypursumary".equals(objName)) {
            List<Map<String, Object>> data = handlerService.findBySql("select puid  from gq_paypursumary where id=" + id);
            int puid = MapUtils.getIntValue(data.get(0), "puid");
            List<Map<String, Object>> list = handlerService.findBySql("select sum(pricetaxtotal) as pricetaxtotals,sum(applymoney) as applymoneys,sum(paidamt) as paidamts from gq_paypursumary where puid=" + puid+" and id !="+id);

            String pricetaxtotals = MapUtils.getString(list.get(0), "pricetaxtotals");//发票金额合计
            String applymoneys = MapUtils.getString(list.get(0), "applymoneys");//申请金额合计
            String paidamts = MapUtils.getString(list.get(0), "paidamts");//付款金额合计
            Map<String, Object> map = new HashMap<>();
            map.put("id", puid);
            //汇总申请金额，付款金额，发票金额
            if (!ToolUtil.isEmpty(pricetaxtotals)) {
                map.put("pricetaxtotals", pricetaxtotals);
            }
            if (!ToolUtil.isEmpty(applymoneys)) {
                map.put("applymoneys", applymoneys);
            }
            if (!ToolUtil.isEmpty(paidamts)) {
                map.put("paidamts", paidamts);
            }
            //主表汇总发票号字段
            List<Map<String, Object>> list2 = handlerService.findBySql("select pinum from gq_paypursumary where puid=" + puid+" and id !="+id);
            String pinum = "";
            if (CollectionUtils.isNotEmpty(list2)) {
                StringBuffer sb = new StringBuffer();
                for (Map<String, Object> stringObjectMap : list2) {
                    String pinum1 = MapUtils.getString(stringObjectMap, "pinum");
                    if (!sb.toString().contains(pinum1)) {
                        sb.append(",").append(pinum1);
                    }
                }
                pinum = sb.toString().replaceFirst(",", "");
            }else {
                pinum=null;
            }
            map.put("invoicecount",list2.size());//发票张数
            map.put("invoicenums", pinum);//发票号统计
            try {
                handlerService.update("gq_paymentapply", map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if("".equals(objName)){

        }
    }
    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        if ("submit".equals(flowNode.getId()) && op.isFlag()) {
            //增加合同付款流程审批前判断
            //查询接收入库主表gq_concollandpay
            List<Map<String, Object>> list5 = handlerService.findBySql("select * from gq_paymentapply where id=" + id);
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(list5)) {
                //发票金额不能为0
               // System.out.println("发票金额=========="+MapUtils.getString(list5.get(0),"pricetaxtotals"));
                if(ToolUtil.isEmpty(MapUtils.getString(list5.get(0),"pricetaxtotals"))){
                    return "发票金额不能为0";
                }
                String concode = (String) list5.get(0).get("concode");
                String nodecode = (String) list5.get(0).get("contractnodenum");
                //判断是合同付款还是采购付款
                if (ToolUtil.isNotEmpty(concode)) {
                    //判断是否有明细数据
                    try {
//                        List<Map<String, Object>> list3 = handlerService.findBySql("select id from gq_concolldetailed where receivingdetailid=" + id);
////                        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(list3)) {
////                            return "请添加付款明细行数据再提交申请";
////                        }
                        String sqlrecord = "select concode as concode, receivingdetailid, contractnodenum, sum(shouldpaying) as shouldpaying,sum(receivingamount) as receivingamount" +
                                "  from gq_concolldetailed group by concode,contractnodenum,receivingdetailid  HAVING concode = '" + concode + "' and contractnodenum='" + nodecode + "' and receivingdetailid in (select id from gq_paymentapply )";

                        List<Map<String, Object>> listrecord = handlerService.findBySql(sqlrecord);
                        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(listrecord)) {
                            String receivingamount = MapUtils.getString(listrecord.get(0), "receivingamount");//此次累计收付款金额
                            if (ToolUtil.isEmpty(receivingamount)) {
                                receivingamount = "0";
                            }
                            String receivingamounttax = MapUtils.getString(list5.get(0), "receivingamounttax");//节点收付款金额
                            if (ToolUtil.isEmpty(receivingamounttax)) {
                                receivingamounttax = "0";
                            }
                            String sumamounttax = MapUtils.getString(list5.get(0), "sumamounttax");//节点累计收付款金额
                            if (ToolUtil.isEmpty(sumamounttax)) {
                                sumamounttax = "0";
                            }
                            BigDecimal sumamounttaxs = new BigDecimal(sumamounttax);//
                            BigDecimal receivingamounts = new BigDecimal(receivingamount);
                            BigDecimal receivingamounttaxs = new BigDecimal(receivingamounttax);
                            if (receivingamounttaxs.compareTo(receivingamounts.add(sumamounttaxs)) < 0) {
                                //return "收付款明细汇总跟节点收付款不相等，请修改明细在提交";
                                return "节点累计收付款金额不能大于节点收付款金额";
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    List<Map<String, Object>> list = handlerService.findBySql("select pinum, inid, applymoney  from gq_paypursumary where puid = " + id);
                    if (CollectionUtils.isNotEmpty(list)) {
                        for (Map<String, Object> stringObjectMap : list) {
                            //获取该行发票号，查询所有提交的这个发票号的总和
                            String pinum = MapUtils.getString(stringObjectMap,"pinum");//发票号
                            int inid = MapUtils.getIntValue(stringObjectMap, "inid");
                          String applymoney = MapUtils.getString(stringObjectMap, "applymoney");//本次申请金额
                            if (ToolUtil.isEmpty(applymoney)) {
                                applymoney = "0";
                            }
                            BigDecimal money = new BigDecimal(applymoney);
                            List<Map<String, Object>> list2 = handlerService.findBySql("select itemnum,pricetaxtotal, applymoney  from gq_invoicepursummary where id = " + inid);
                            if (CollectionUtils.isNotEmpty(list2)) {
                                String pricetaxtotal = MapUtils.getString(list2.get(0), "pricetaxtotal");//发票含税金额
                                if (ToolUtil.isEmpty(pricetaxtotal)) {
                                    pricetaxtotal = "0";
                                }
                                BigDecimal pricetaxtotals = new BigDecimal(pricetaxtotal);
//                                String applymoney1 = MapUtils.getString(list2.get(0), "applymoney");//发票累计申请金额
//                                if (ToolUtil.isEmpty(applymoney1)) {
//                                    applymoney1 = "0";
//                                }
                                String applymoney1 = null;//发票累计申请金额,包含所有提交的数据
                                List<Map<String, Object>> list6 = handlerService.findBySql(" select sum(applymoney) as applymoney from gq_paypursumary where pinum = '"+pinum+"' and  puid in (select id from gq_paymentapply where status = '审批中' or status = '已审批')");
                                if(CollectionUtils.isNotEmpty(list6)&&ToolUtil.isNotEmpty(list6.get(0))){
                                    applymoney1= MapUtils.getString(list6.get(0), "applymoney");//本次申请金额
                                }
                                if (ToolUtil.isEmpty(applymoney1)) {
                                    applymoney1 = "0";
                                }
                                BigDecimal applymoneys = new BigDecimal(applymoney1);
                                String itemnum = MapUtils.getString(list2.get(0), "itemnum");
                                applymoneys = applymoneys.add(money);
                                //如果累计申请金额大于 含税金额，给出提示
                                System.out.println("applymoneys===="+applymoneys);
                                System.out.println("pricetaxtotals===="+pricetaxtotals);
                                System.out.println("applymoneys.compareTo(pricetaxtotals)===="+applymoneys.compareTo(pricetaxtotals));
                                if (applymoneys.compareTo(pricetaxtotals) == 1) {
                                    return "物料编号为" + itemnum + "的数据行，含税金额不能小于累计申请金额";
                                    //throw new ServiceException("物料编号为" + itemnum + "的数据行，含税金额不能小于累计申请金额");
                                }
                            }
                        }
                    }
                }
            }
        }

        return super.beforeExcuteFlow(app, id, flowNode, op);
    }

    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {

        //-----------------------审批后代码逻辑------------------
        /*
         * 4、引用系统发票条件：发票金额<累计申请金额；付款申请单保存时，需回写对应发票申请金额；
         * 5. 申请金额需要回写到采购订单中汇总里的 已付金额
         * 主表 aa 子表 bb  字段 applymoney
         * */

        try {
            if ("approval".equals(flowNode.getId()) && op.isFlag()) {
                List<Map<String, Object>> list5 = handlerService.findBySql("select * from gq_paymentapply where id=" + id);
                if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(list5)) {
                    String concode = (String) list5.get(0).get("concode");
                    //判断是合同付款还是采购付款，根据合同编号是否为空
                    if (ToolUtil.isNotEmpty(concode)) {
                        try {
                            setConNodeInfo(app, id, flowNode, op,"gq_paymentapply","合同付款");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        List<Map<String, Object>> list = handlerService.findBySql("select inid, applymoney,poslid  from gq_paypursumary where puid = " + id);
                        if (CollectionUtils.isNotEmpty(list)) {
                            for (Map<String, Object> stringObjectMap : list) {
                                int inid = MapUtils.getIntValue(stringObjectMap, "inid");
                                int poslid = MapUtils.getIntValue(stringObjectMap, "poslid");

                                String applymoney = MapUtils.getString(stringObjectMap, "applymoney");//申请金额
                                if (ToolUtil.isEmpty(applymoney)) {
                                    applymoney = "0";
                                }
                                String applymoney1="";
                                List<Map<String, Object>> bySql = handlerService.findBySql("select applymoney from gq_invoicepursummary where id=" + inid);
                                if (CollectionUtils.isNotEmpty(bySql)){
                                    Map<String, Object> map = bySql.get(0);
                                    applymoney1 = MapUtils.getString(map, "applymoney");
                                    if (applymoney1==""||applymoney1==null){
                                        applymoney1="0";
                                    }
                                }
                                BigDecimal bigDecimal = new BigDecimal(applymoney1);
                                BigDecimal bigDecimal1 = new BigDecimal(applymoney);
                                BigDecimal bigDecimal2 = new BigDecimal("0");
                                bigDecimal2=bigDecimal1.add(bigDecimal);
                                //回写发票申请金额
                                handlerService.updateBySql("update gq_invoicepursummary set applymoney = "+bigDecimal2+" where id = " + inid);
                                List<Map<String, Object>> bySql1 = handlerService.findBySql("select applymoney,pricetaxtotal from gq_invoicepursummary where id = " + inid);
                                if (CollectionUtils.isNotEmpty(bySql1)){
                                    Map<String, Object> map = bySql1.get(0);
                                    String applymoney2 = MapUtils.getString(map, "applymoney");
                                    String pricetaxtotal = MapUtils.getString(map, "pricetaxtotal");
                                    BigDecimal bigDecimal3 = new BigDecimal(applymoney2);//申请金额
                                    BigDecimal bigDecimal4 = new BigDecimal(pricetaxtotal);//含税金额
                                    BigDecimal bigDecimal5 = new BigDecimal("0");
                                    bigDecimal5=bigDecimal4.subtract(bigDecimal3);
                                    handlerService.updateBySql("update gq_invoicepursummary set faplymoney = "+bigDecimal5+" where id = " + inid);
                                }
                                //修改采购订单汇总行，累计已收金额
                                handlerService.updateBySql("update gq_posline set paidamts = paidamts+" + applymoney + ",unpaidamts = unpaidamts -" + applymoney + " where id = " + poslid);
                            }
                        }
                        try {
                            List<Map<String, Object>> list2 = handlerService.findBySql("select  invoicemoney,ponum  from gq_purchaseinvoice where id = " + id);
                            if (CollectionUtils.isNotEmpty(list2)) {
                                //修改采购订单主表，累计开票金额  采购接收那边累计可开票金额
                                handlerService.updateBySql("update gq_po set paidamts= paidamts+" + list2.get(0).get("invoicemoney") + ",unpaidamt=unpaidamt-" + list2.get(0).get("invoicemoney") + " where ponum=" + list2.get(0).get("ponum"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


//        if ("complete".equals(flowNode.getId()) && op.isFlag()){
////            // 查询采购管理付款申请信息
////            List<Map<String, Object>> ppaList = handlerService.findBySql("select * from gq_paymentapply where id = " + id);
////            Map<String, Object> ppaMap = ppaList.get(0);
////            Integer poid = MapUtils.getInteger(ppaMap, "poid");
////            Float invoiceamt = MapUtils.getFloat(ppaMap, "invoiceamt");
////            String invoicenums = MapUtils.getString(ppaMap, "invoicenums");
////
////            // 更新采购订单付款金额，待付款金额
////            handlerService.updateBySql("update gq_po set paidamt = paidAmt + " + invoiceamt + ", unpaidamt = unpaidamt - " + invoiceamt + " where id = " + poid);
////
////            // 更新采购发票状态
////            if (StringUtils.isNotEmpty(invoicenums)) {
////                handlerService.updateBySql("update gq_purchaseinvoice set status = '已使用' where find_in_set(pinum, '" +invoicenums+ "')");
////            }
////        }
    }

    public void setConNodeInfo(String app, Long id, FlowNode flowNode, FlowOpinion op,String tableName,String bizName) throws Exception {
        //查询接收入库主表gq_concollandpay
        List<Map<String, Object>> list = handlerService.findBySql("select * from "+tableName+" where id=" + id);
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(list)) {
            Map<String, Object> paymap = list.get(0);
            // 调用成本归集
            //costAccumulation(paymap);

            //(1)将上传的文件，添加到合同台账里边
            String concode = (String) paymap.get("concode");
            //创建人
            String createuser = MapUtils.getString(paymap,"createuser");
            String createuserdesc = MapUtils.getString(paymap,"createuserdesc");
            String deptcode = MapUtils.getString(paymap,"deptcode");
            System.out.println("concode==============" + concode);
            fileSynUtilService.insertFiles(app, id, concode);
            //审批通过后，将节点状态修改成执行中，或者已完成
            String nodecode = (String) paymap.get("contractnodenum");
            //合同节点金额
            double receivingamounttax = MapUtils.getDoubleValue(list.get(0),"receivingamounttax");
            //收付款节点累计已收金额
            double alreceivingamount=0l;
            //（2）流程归档
            fileSynUtilService.processarc(app, id + "", bizName, concode, (String) list.get(0).get("conname"));

            //累计收款金额是否等于节点付款金额
            boolean ispayend = false;

            //(3)增加收付款记录
            String sqlrecord = "select sum(a.receivingamount) as receivingamount  from( select concode as concode, receivingdetailid, contractnodenum, sum(shouldpaying) as shouldpaying,sum(receivingamount) as receivingamount" +
                    "  from gq_concolldetailed group by concode,contractnodenum,receivingdetailid HAVING concode = '" + concode + "' and contractnodenum='" + nodecode + "'  and receivingdetailid in (select id from "+tableName+"    where status = '已批准')) a";

            List<Map<String, Object>> listrecord = handlerService.findBySql(sqlrecord);
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(listrecord)&&listrecord.get(0)!=null) {
                Map<String, Object> map = new HashMap<>();
                map.put("receivingdetailid", id);//主表主键，关联关系查询需要
                map.put("concode", concode);
                map.put("type", list.get(0).get("contracttype"));//收付款类型
                map.put("paymethod", list.get(0).get("receivingway"));
                map.put("conname", list.get(0).get("conname"));
                map.put("contractnodenum", nodecode);//合同节点编号
                map.put("receivingamount", listrecord.get(0).get("receivingamount"));//已收金额
                //map.put("shouldpaying", listrecord.get(0).get("shouldpaying"));//应收金额
                map.put("shouldpaying", list.get(0).get("receivingamounttax"));//合同节点金额(应收金额)

                double receivingamount = MapUtils.getDoubleValue(listrecord.get(0),"receivingamount");
                map.put("remainingamount", receivingamounttax-receivingamount);//剩余金额
                map.put("createuser",createuser);
                map.put("createuserdesc",createuserdesc);
                map.put("deptcode",deptcode);
                //System.out.println("createuser================"+createuser);
                handlerService.insert("gq_concollrecord", map);
                //节点已收金额赋值
                alreceivingamount=MapUtils.getDouble(listrecord.get(0),  "receivingamount");
                //receivingamounts = MapUtils.getString(listrecord.get(0), "receivingamount");
            }
            //（4）查询付款节点 节点金额用于跟累计收付款额进行比较，判断节点是否完成
            String constatus = "待收款";
            if("gq_paymentapply".equals(tableName)){
                constatus = "待付款";
            }
            if (receivingamounttax<=alreceivingamount) {
                ispayend = true;
                constatus="已完成";
                //更新主表，是否完成收款字段
                handlerService.updateBySql("update "+tableName +" set complete = '是' where id="+id);
            }

            //(5)修改合同节点状态和累计收款或者付款金额
            String sql = "update gq_connodenew set status = '"+constatus+"',alreceivingamount = "+alreceivingamount+" where concode = '" + concode + "' and nodecode = '" + nodecode + "'";
            handlerService.updateBySql(sql);
            //（6）合同收付款信息汇总 先查询，如果为空，插入，如果不为空，修改
            Map<String, Object> map = new HashMap<>();
            map.put("nid",id);//主表主键 关联关系查询需要
            //修改
            String sql2 = " select max(a.shouldpaying) as shouldpaying,sum(a.receivingamount) as receivingamount  from ( select max(conname) as conname, concode,max(type) as type, max(totalprice) as shouldpaying,sum(receivingamount) as receivingamount,receivingdetailid " +
                    " from gq_concolldetailed" +
                    " GROUP BY concode,receivingdetailid having concode = '" + concode + "' and receivingdetailid in (select id from "+tableName+" where status = '已批准' ) )a";

            List<Map<String, Object>> list2 = handlerService.findBySql(sql2);
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(list2)) {
                String sql4 = "select concode, group_concat(nodecode) as nodecode,max(status) as status from (select concode,nodecode,status  from gq_connodenew where status = '已完成'  and ispaynode = '是') as cp \n" +
                        " GROUP BY concode having concode = '" + concode + "'" +
                        " union all" +
                        " select concode as a, group_concat(nodecode) as b,max(status) as c from (select concode,nodecode,status  from gq_connodenew where status != '已完成'  and ispaynode = '是') as cp \n" +
                        " GROUP BY concode having concode = '" + concode + "'";
                List<Map<String, Object>> list4 = handlerService.findBySql(sql4);
                if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(list4)) {
                    for (Map<String, Object> map1 : list4) {
                        if ("已完成".equals(map1.get("status"))) {
                            map.put("alnodecode", map1.get("nodecode"));//已完成收付款节点
                        } else {
                            map.put("surplusnodecode", map1.get("nodecode"));//剩余收付款节点
                        }
                    }
                    map.put("shouldpaying", list2.get(0).get("shouldpaying"));//应收付款额
                    map.put("receivingamount", list2.get(0).get("receivingamount"));//已收付款额
                    map.put("type", list.get(0).get("receivingtype"));//收付款类型
                    map.put("conname", list.get(0).get("conname"));//合同名称
                    map.put("concode", list.get(0).get("concode"));//合同编号
                    map.put("createuser",createuser);
                    map.put("createuserdesc",createuserdesc);
                    map.put("deptcode",deptcode);
                }
            }
            //每次收付款都应该是新增一条合同收付款汇总信息
            //System.out.println("createuser================"+createuser);
            handlerService.insert("gq_paysummary", map);
//            String sql3 = "select * from gq_paysummary where concode = '" + concode + "'";
//            List<Map<String, Object>> list3 = handlerService.findBySql(sql3);
//            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(list3)) {
//                map.put("id", list3.get(0).get("id"));
//                if(ToolUtil.isEmpty(map.get("surplusnodecode"))){
//                    map.put("surplusnodecode","无");
//                }
//                handlerService.update("gq_paysummary", map);
//            } else {
//
//            }

            //审批通过后，将节点状态修改成已完成  只有当付款金额累计等于节点金额时，节点才可以修改为已完成

            if (ispayend) {
                //（7）更新合同节点进度--对应进度条信息
                try {
                    fileSynUtilService.updateprocess(concode);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //（8）更新合同台账，合同卡片剩余收付款节点
                try {
                    int nums = 0;
                    String surplusnode = (String) map.get("surplusnodecode");
                    if (ToolUtil.isNotEmpty(surplusnode)) {
                        nums = surplusnode.split(",").length;
                    }

                    String upd = "update gq_conaccount set surplusnode ='" + nums + "' where concode = '" + concode + "'";
                    handlerService.updateBySql(upd);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        }
    }

    /**
     * 采购台账 付款申请
     * @param app
     * @param type
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public Object operate(String app, String type, Map<String, Object> params) throws Exception {
        if(app.equals("paymentapplyApp")){
            if(type.equals("paymentapplyByPo")){
                String poid = MapUtils.getString(params, "poid");//采购订单id
                List<Map<String, Object>> bySql = handlerService.findBySql("SELECT DISTINCT a.payapplynum,a.* FROM gq_paymentapply a LEFT JOIN gq_paypursumary b ON b.puid = a.id left JOIN gq_purchaseinvoice c on b.pinum = c.pinum LEFT JOIN gq_po d on c.ponum=d.ponum where d.id= '" + poid + "'");
                return bySql;
            }
        }
        return super.operate(app, type, params);
    }
}
